@page "/logs"
@inject ILogService LogService
@inject IJSRuntime JSRuntime

<PageTitle>系统日志</PageTitle>

<div>
    <Title Level="2">系统日志</Title>
    
    <div style="margin: 16px 0;">
        <Space>
            <SpaceItem>
                <span>日志级别：</span>
                <Select @bind-Value="selectedLevel"
                        Placeholder="全部级别"
                        TItemValue="string"
                        TItem="string"
                        Style="width: 120px;"
                        OnSelectedItemChanged="OnLevelChanged"
                        AllowClear="true">
                    <SelectOptions>
                        <SelectOption Value="@("Info")" Label="Info" TItemValue="string" TItem="string" />
                        <SelectOption Value="@("Warning")" Label="Warning" TItemValue="string" TItem="string" />
                        <SelectOption Value="@("Error")" Label="Error" TItemValue="string" TItem="string" />
                        <SelectOption Value="@("Debug")" Label="Debug" TItemValue="string" TItem="string" />
                    </SelectOptions>
                </Select>
            </SpaceItem>
            <SpaceItem>
                <Button Icon="reload" OnClick="RefreshLogs">
                    刷新
                </Button>
            </SpaceItem>
            <SpaceItem>
                <Button Icon="download" OnClick="ExportLogs">
                    导出日志
                </Button>
            </SpaceItem>
            <SpaceItem>
                <Popconfirm Title="确定要清空所有日志吗？" 
                            OnConfirm="ClearLogs"
                            OkText="确定" 
                            CancelText="取消">
                    <Button Danger Icon="delete">
                        清空日志
                    </Button>
                </Popconfirm>
            </SpaceItem>
        </Space>
    </div>
    
    @if (loading)
    {
        <Spin Spinning="true" Size="large">
            <div style="height: 300px;"></div>
        </Spin>
    }
    else if (displayLogs?.Any() == true)
    {
        <Table DataSource="displayLogs" 
               TItem="LogEntry" 
               Bordered="true" 
               Size="TableSize.Small"
               PageSize="20"
               ScrollY="@("500px")"
               Responsive>
            <PropertyColumn Property="l => l.Timestamp" Title="时间" Format="yyyy-MM-dd HH:mm:ss" Width="@("180px")" />
            <PropertyColumn Property="l => l.Level" Title="级别" Width="@("80px")">
                <Tag Color="@GetLevelColor(context.Level)">@context.Level</Tag>
            </PropertyColumn>
            <PropertyColumn Property="l => l.Module" Title="模块" Width="@("120px")" />
            <PropertyColumn Property="l => l.Message" Title="消息" />
            <ActionColumn Title="操作" Width="@("80px")">
                @if (!string.IsNullOrEmpty(context.Details))
                {
                    <Button Type="@ButtonType.Link" Size="small" OnClick="() => ShowDetails(context)">
                        详情
                    </Button>
                }
            </ActionColumn>
        </Table>
    }
    else
    {
        <Empty Description="@("暂无日志记录")" />
    }
</div>

<!-- 日志详情对话框 -->
<Modal Title="日志详情"
       Visible="showDetailsModal"
       OnCancel="CloseDetailsModal"
       Footer="null"
       Width="@("800px")">
    @if (selectedLog != null)
    {
        <Descriptions Bordered>
            <DescriptionsItem Title="时间">
                @selectedLog.Timestamp.ToString("yyyy-MM-dd HH:mm:ss")
            </DescriptionsItem>
            <DescriptionsItem Title="级别">
                <Tag Color="@GetLevelColor(selectedLog.Level)">@selectedLog.Level</Tag>
            </DescriptionsItem>
            <DescriptionsItem Title="模块">
                @selectedLog.Module
            </DescriptionsItem>
            <DescriptionsItem Title="消息" Span="3">
                @selectedLog.Message
            </DescriptionsItem>
            @if (!string.IsNullOrEmpty(selectedLog.Details))
            {
                <DescriptionsItem Title="详细信息" Span="3">
                    <pre style="white-space: pre-wrap; font-family: monospace; background: #f5f5f5; padding: 8px; border-radius: 4px;">@selectedLog.Details</pre>
                </DescriptionsItem>
            }
        </Descriptions>
    }
</Modal>

@code {
    private List<LogEntry>? allLogs;
    private List<LogEntry>? displayLogs;
    private bool loading = true;
    private string selectedLevel = "";
    private bool showDetailsModal = false;
    private LogEntry? selectedLog;
    
    protected override async Task OnInitializedAsync()
    {
        await LoadLogs();
    }
    
    private async Task LoadLogs()
    {
        try
        {
            loading = true;
            allLogs = await LogService.GetLogsAsync();
            FilterLogsByLevel();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"加载日志失败: {ex.Message}");
        }
        finally
        {
            loading = false;
            StateHasChanged();
        }
    }
    
    private void FilterLogs()
    {
        FilterLogsByLevel();
        StateHasChanged();
    }
    
    private void OnLevelChanged(string level)
    {
        selectedLevel = level;
        FilterLogsByLevel();
        StateHasChanged();
    }
    
    private void FilterLogsByLevel()
    {
        if (allLogs == null) return;
        
        if (string.IsNullOrEmpty(selectedLevel))
        {
            displayLogs = allLogs.OrderByDescending(l => l.Timestamp).ToList();
        }
        else
        {
            displayLogs = allLogs.Where(l => l.Level == selectedLevel)
                                .OrderByDescending(l => l.Timestamp).ToList();
        }
    }
    
    private async Task RefreshLogs()
    {
        await LoadLogs();
    }
    
    private async Task ExportLogs()
    {
        try
        {
            var logContent = await LogService.ExportLogsAsync();
            var fileName = $"system_logs_{DateTime.Now:yyyyMMdd_HHmmss}.txt";
            
            await JSRuntime.InvokeVoidAsync("downloadFile", fileName, logContent);
            await LogService.LogInfoAsync("导出系统日志", "Logs");
        }
        catch (Exception ex)
        {
            await LogService.LogErrorAsync($"导出日志失败: {ex.Message}", "Logs");
        }
    }
    
    private async Task ClearLogs()
    {
        try
        {
            await LogService.ClearLogsAsync();
            await LoadLogs();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"清空日志失败: {ex.Message}");
        }
    }
    
    private void ShowDetails(LogEntry log)
    {
        selectedLog = log;
        showDetailsModal = true;
    }
    
    private void CloseDetailsModal()
    {
        showDetailsModal = false;
        selectedLog = null;
    }
    
    private string GetLevelColor(string level)
    {
        return level switch
        {
            "Info" => "blue",
            "Warning" => "orange",
            "Error" => "red",
            "Debug" => "purple",
            _ => "default"
        };
    }
} 